import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, message, Form, Input, Select } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import { redispoolSearch, redispoolDataSearch } from '@/services/server';
import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';

import styles from './style.less';

const SensitizeManageList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelCodeVisible, setModelCodeVisible] = useState<boolean>(false);
  const [modalCodeForm] = Form.useForm();

  // 跳编辑页
  const hanldleEdit = (record: any) => {
    history.push(`/server/redisConfig/modify/${record.id}`);
  };

  const columns: ProColumns<API.RedispoolListItem>[] = [
    // 表单
    {
      title: 'redisIP地址',
      dataIndex: 'redisIP',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '端口号',
      dataIndex: 'redisPort',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '服务器名称',
      dataIndex: 'redisDesc',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    // 表格
    {
      title: 'id',
      dataIndex: 'id',
      ellipsis: true,
      width: 60,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: 'RedisIP地址',
      dataIndex: 'redisIp',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '端口号',
      dataIndex: 'redisPort',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '服务器名称',
      dataIndex: 'redisDesc',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '类型',
      dataIndex: 'redisType',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '服务器标识',
      dataIndex: 'siteTag',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '最大链接数',
      dataIndex: 'maxTotal',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
      // valueEnum: {
      //   0: { text: '不需要' },
      //   1: { text: '需要' },
      // },
    },
    {
      title: '最大空闲链接数',
      dataIndex: 'maxIdle',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '最大等待时间',
      dataIndex: 'maxWait',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: 'borrow有效检查',
      dataIndex: 'testOnBorrow',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
      render: (text: any, record: any) => (record.testOnBorrow ? 'true' : 'false'),
    },
    {
      title: 'return有效检查',
      dataIndex: 'testOnReturn',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
      render: (text: any, record: any) => (record.testOnReturn ? 'true' : 'false'),
    },
    {
      title: '备用Redis地址',
      dataIndex: 'otherRedisIp',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: 'Redis1IP地址',
      dataIndex: 'redis1Cluster',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: 'Redis2IP地址',
      dataIndex: 'redis2Ip',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: 'Redis3IP地址',
      dataIndex: 'redis3Cluster',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: 'Redis4IP地址',
      dataIndex: 'redis4Cluster',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 80,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => hanldleEdit(record)}>修改</a>&nbsp;&nbsp;
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: any = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await redispoolSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const toAddPage = async () => {
    history.push(`/server/redisConfig/add`);
  };

  const handleCodeCancel = () => {
    setModelCodeVisible(false);
    modalCodeForm.resetFields();
  };

  const handleCodeOK = async () => {
    modalCodeForm.validateFields().then(async (values) => {
      setConfirmLoad(true);
      console.log('批量激活--values', values);
      const res = await redispoolDataSearch({
        key: values.key,
        server: values.server,
      });
      if (res.code === 200 && res.data) {
        modalCodeForm.setFieldsValue({
          ...values,
          value: res.data.value,
          seconds: res.data.seconds,
        });
      } else {
        message.info(res.message || '未查询到数据');
        modalCodeForm.setFieldsValue({
          ...values,
          value: '',
          seconds: '',
        });
      }
      setConfirmLoad(false);
    });
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.RedispoolListItem>
          manualRequest={true}
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          // @ts-ignore
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          toolBarRender={() => [
            <Button type="primary" key="add" onClick={() => toAddPage()}>
              新增
            </Button>,
            <Button type="primary" key="query" onClick={() => setModelCodeVisible(true)}>
              数据查询
            </Button>,
          ]}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />

        <Modal
          title="查询数据"
          width={520}
          open={modelCodeVisible}
          footer={null}
          // onOk={handleCodeOK}
          onCancel={handleCodeCancel}
          // cancelText="关闭"
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalCodeForm}
            initialValues={{
              key: '',
              server: 1,
              value: '',
              seconds: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              label="RedisKey"
              name="key"
              rules={[{ required: true, message: '不得为空' }]}
            >
              <Input placeholder="RedisKey" />
            </Form.Item>
            <Form.Item
              label="RedisServer"
              name="server"
              rules={[{ required: true, message: '不得为空' }]}
            >
              <Select
                options={[
                  { label: 'Redis1', value: 1 },
                  { label: 'Redis3', value: 3 },
                  { label: 'Redis4', value: 4 },
                ]}
              />
            </Form.Item>
            <div
              style={{
                width: '100%',
                display: 'flex',
                justifyContent: 'flex-end',
                marginBottom: 24,
              }}
            >
              <Button type="primary" onClick={handleCodeOK} loading={confirmLoad}>
                确认
              </Button>
            </div>
            <Form.Item label="效期(秒)" name="seconds">
              <Input placeholder="seconds" disabled />
            </Form.Item>
            <Form.Item label="RedisValue" name="value">
              <Input.TextArea rows={4} placeholder="" disabled />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageList;
